package com.fzn3.day07;

import java.util.Iterator;

/**
 * @author fzn
 * 描述：
 * @program DataStructure
 * @create 2023/3/13 16:00
 **/
public class ArrayStack<E> implements Stack<E>, Iterable<E> {

    private E[] array;
    // 指针
    private int top;

    /**
     * 底部           顶
     * 0   1   2   3
     *
     * @param capacity
     */
    @SuppressWarnings("all")
    public ArrayStack(int capacity) {
        this.array = (E[]) new Object[capacity];
    }

    @Override
    public boolean push(E value) {
        if (isFull()) return false;
        array[top++] = value;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()) return null;
        return array[--top];
    }

    @Override
    public E peek() {
        if (isEmpty()) return null;
        return array[top - 1];
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public boolean isFull() {
        return top == array.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = top;

            @Override
            public boolean hasNext() {
                return p > 0;
            }

            @Override
            public E next() {
                return array[--p];
            }
        };
    }
}
